package de.lang.rollo.controller.model.daos;

import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.mongojack.JacksonDBCollection;
import org.mongojack.WriteResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.pi4j.io.gpio.RaspiPin;

import de.lang.rollo.controller.logic.GPIOFacade;
import de.lang.rollo.controller.managed.MongoManaged;
import de.lang.rollo.controller.model.RolloEvent;
import de.lang.rollo.controller.model.RolloMotor;
import de.lang.rollo.controller.model.Schalter;

public class SchalterDAO {
	private static Logger logger = LoggerFactory.getLogger(SchalterDAO.class);
	
	private JacksonDBCollection<RolloEvent, String> events;
	private JacksonDBCollection<RolloMotor, String> motoren;
	private JacksonDBCollection<Schalter, String> schalter;

	public SchalterDAO() {
		events = MongoManaged.getEvents();
		motoren = MongoManaged.getMotoren();
		schalter = MongoManaged.getSchalter();
	}

	private Schalter fetch(Schalter schalter) {
		schalter.setMotor(motoren.findOneById(schalter.getMotor_id()));
		return schalter;
	}

	public List<Schalter> getAllSchalter() {
		List<Schalter> list = schalter.find().toArray();
		Iterator<Schalter> it = list.iterator();
		while (it.hasNext()) {
			Schalter s = it.next();
			fetch(s);
		}
		return list;
	}

	public String insertSchalter(Schalter s) {
		if (s.getId() != null)
			return null;
		if (s.getMotor() != null) {
			if (s.getMotor_id() == null || 
					motoren.findOneById(s.getMotor_id()) == null) {
				WriteResult<RolloMotor, String> result = motoren.insert(s
						.getMotor());
				s.getMotor().setId(result.getSavedId());
				s.setMotor_id(result.getSavedId());
			}
			
			WriteResult<Schalter, String> result2 = schalter.insert(s);
			s.setId(result2.getSavedId());
			return result2.getSavedId();
		}
		return null;

	}
	
	public String updateSchalter(Schalter s){
		if (s.getId() == null)
			return null;
		if (s.getMotor() != null) {
			if (s.getMotor_id() == null || 
					motoren.findOneById(s.getMotor_id()) == null) {
				WriteResult<RolloMotor, String> result = motoren.insert(s
						.getMotor());
				s.getMotor().setId(result.getSavedId());
				s.setMotor_id(result.getSavedId());
			}
//			schalter.removeById(s.getId());
			WriteResult<Schalter, String> result2 = schalter.updateById(s.getId(), s);
//			s.setId(result2.getSavedId());
			return s.getId();
		}
		return null;
	}

}
